<template>
	<div class="app-sheet-container">
		<div v-if="enableDesign" class="app-sheet__button">
			<a-upload :before-upload="loadJson" :maxCount="1" :showUploadList="false">
				<a-button
					><i class="fa fa-file-excel-o" />{{
						$t('common.sheet.importjson')
					}}</a-button
				>
			</a-upload>
			<a-button @click="downloadJson()"
				><i class="fa fa-file-excel-o" />{{
					$t('common.sheet.exportjson')
				}}</a-button
			>
		</div>
		<div
			:id="name"
			:class="{ 'app-sheet': true, 'is-disabled': !enableDesign }"
		></div>
	</div>
</template>
<script setup lang="ts">
import { SheetProps } from './sheet';
import LuckyExcel from 'luckyexcel';
const props = defineProps(SheetProps);

// 初始化sheet参数
const initOptions = () => {
	const sheetConfig: any = {
		container: props.name,
		lang: 'zh',
	};
	// 非设计态不显示各种边栏
	if (!props.enableDesign) {
		Object.assign(sheetConfig, {
			showinfobar: false,
			showtoolbar: false,
			showsheetbar: false,
			showstatisticBar: false,
			enableAddRow: false,
			enableAddBackTop: false,
			rowHeaderWidth: 0,
			columnHeaderHeight: 0,
		});
	}
	// 合入用户自定义参数
	if (props.config) {
		Object.assign(sheetConfig, props.config);
	}
	return sheetConfig;
};

onMounted(() => {
	if (luckysheet) {
		const sheetConfig = initOptions();
		luckysheet.create(sheetConfig);
		setTimeout(() => {
			luckysheet.refreshFormula();
		}, 500);
	}
});

watch(
	() => props.config,
	() => {
		if (luckysheet) {
			const sheetConfig = initOptions();
			luckysheet.create(sheetConfig);
			setTimeout(() => {
				luckysheet.refreshFormula();
			}, 500);
		}
	},
	{ immediate: false }
);

const loadJson = (file: any) => {
	let name = file.name;
	let suffixArr = name.split('.'),
		suffix = suffixArr[suffixArr.length - 1];
	if (suffix != 'xlsx') {
		App.getNotificationHelper().warning(
			App.ts('app.notificationtitle.warn'),
			App.ts('common.sheet.notxlsxfiletype')
		);
		return;
	}
	LuckyExcel.transformExcelToLucky(
		file,
		function (exportJson: any, luckysheetfile: any) {
			if (exportJson.sheets == null || exportJson.sheets.length == 0) {
				App.getNotificationHelper().warning(
					App.ts('app.notificationtitle.warn'),
					App.ts('common.sheet.notxlsxfiletype')
				);
				return;
			}
			luckysheet.destroy();
			luckysheet.create({
				container: props.name,
				lang: 'zh',
				data: exportJson.sheets,
			});
		}
	);
};

const downloadJson = () => {
	const exportJson = luckysheet.getAllSheets();
	// todo
	console.log(exportJson, '导出json');
};
</script>
